<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Tn-eltable Example</title>
    <script
      type="text/javascript"
      src="https://unpkg.zhimg.com/vue@2.6.12/dist/vue.js"
    ></script>
    <!-- 引入样式 -->
    <link
      rel="stylesheet"
      href="https://unpkg.zhimg.com/element-ui@2.15.6/lib/theme-chalk/index.css"
    />
    <!-- 引入组件库 -->
    <script src="https://unpkg.zhimg.com/element-ui@2.15.6/lib/index.js"></script>
    <script type="text/javascript" src="../dist/tn-element-ui.js"></script>
    <style>
      .list {
        display: flex;
        flex-direction: column;
        height: 400px;
      }
      .list-title {
        line-height: 20px;
        padding: 8px;
        font-weight: bold;
        border-top: 1px solid #ebeef5;
        border-left: 1px solid #ebeef5;
        border-right: 1px solid #ebeef5;
      }
      .list-handle-bar {
        border-top: 1px solid #ebeef5;
        border-left: 1px solid #ebeef5;
        border-right: 1px solid #ebeef5;
      }
      .list-handle-bar > div {
        padding: 8px;
      }
      .table-wrapper {
        flex-grow: 1;
      }
      .show {
        display: block;
      }
      .hide {
        display: none;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <h2>TnEltable</h2>
      <hr />
      <div class="list" style="height: 800px">
        <div class="list-title">
          columns(button column, render), autoHeight, display: none
        </div>
        <div class="list-handle-bar">
          <div>
            <el-switch
              v-model="tableIsShow"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
            <span>{{ tableIsShow ? '隐藏' : '显示' }}table</span>
          </div>
          <div>
            <el-switch
              v-model="isShowDelBtn"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
            <span
              >{{ isShowDelBtn ? '显示' : '隐藏' }}delete button hidden: () =>
              _this.isShowDelBtn
            </span>
            <el-divider direction="vertical"></el-divider>
            <span>编辑按钮 hidden: row => row.value</span>
            <el-divider direction="vertical"></el-divider>
            <span>新增按钮 默认状态</span>
          </div>
          <div>
            <el-button v-on:click="testColumnsUpdate"
              >test columns update</el-button
            >
            <el-divider direction="vertical"></el-divider>
            <span>任务名: {{ taskName }}</span>
          </div>
          <div>
            <el-button @click="changeTableDataHandler">change table data(fix: data change bodyWrapper scroll no reset test)</el-button>
          </div>
        </div>
        <div class="table-wrapper" :class="`${tableIsShow ? 'show' : 'hide'}`">
          <tn-eltable
            ref="tn-eltable"
            :data="list"
            :columns="columns"
            border
            @selection-change="handleSelectionChange"
            @button-click="handleButtonClick"
            show-summary
            :summary-method="getSummaries"
          />
        </div>
      </div>
      <div class="list">
        <div class="list-title">slot</div>
        <div class="table-wrapper">
          <tn-eltable
            :data="list"
            border
            @selection-change="handleSelectionChange"
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column type="selection" width="100"> </el-table-column>
            <el-table-column type="index" label="index" width="100">
            </el-table-column>
            <el-table-column prop="name" label="name-prop"></el-table-column>
            <el-table-column prop="value" label="value"></el-table-column>
            <el-table-column label="name-caption-string">111</el-table-column>
            <el-table-column label="name-caption-fn">
              <template slot-scope="scope">{{ getName(scope.row) }}</template>
            </el-table-column>
            <el-table-column label="name-caption-invalid">--</el-table-column>
            <el-table-column label="button">
              <template slot-scope="scope">
                <el-button
                  @click="handleButtonClick('update', scope.$index, scope.row)"
                  >编辑</el-button
                >
                <el-button
                  @click="handleButtonClick('delete', scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </tn-eltable>
          <el-pagination
            :page-sizes="[5, 10, 20, 40]"
            :page-size="100"
            layout="pager,sizes,total"
            :total="1000"
          />
        </div>
      </div>
    </div>

    <script type="text/javascript">
      const JsGlobalConstants = [null, undefined, 0, 1, '"0"', true, false]

      Vue.directive('bgcolor', {
        inserted: function (el, { value }) {
          if (value) {
            el.style.backgroundColor = value
            el.style.color = 'white'
          }
        },
      })

      var app = new Vue({
        el: '#app',
        data() {
          const _this = this
          return {
            tableIsShow: false,
            isShowDelBtn: false,
            columns: [
              {
                key: 'selection',
                type: 'selection',
              },
              {
                key: 'index',
                label: 'index',
                width: 100,
                type: 'index',
              },
              {
                key: 'name-prop',
                prop: 'name',
                label: 'name-prop',
              },
              {
                key: 'value',
                label: 'String(value)',
                // caption 优先级高与 prop
                prop: 'value',
                caption: function (row) {
                  return String(row.value)
                },
              },
              {
                key: 'noEmptyCellValue',
                label: 'noEmptyCellValue(default)',
                prop: 'value',
              },
              {
                key: 'name-caption-string',
                label: 'name-caption-string',
                caption: '111',
              },
              {
                key: 'name-caption-fn',
                label: 'name-caption-fn',
                caption: _this.getName,
              },
              {
                key: 'name-caption-invalid',
                label: 'name-caption-invalid',
              },
              // type: button
              {
                key: 'button',
                label: 'button',
                type: 'button',
                'min-width': 130,
                buttons: [
                  {
                    hidden: (row) => row.value,
                    key: 'update',
                    caption: '编辑',
                  },
                  {
                    hidden: () => _this.isShowDelBtn,
                    key: 'delete',
                    caption: '删除',
                  },
                  {
                    key: 'add',
                    caption: '新增',
                  },
                ],
              },
              {
                key: 'button--len-0',
                label: 'button--len-0',
                type: 'button',
                'min-width': 60,
                emptyCellValue: '无数据',
                buttons: [
                  {
                    hidden: () => _this.isShowDelBtn,
                    key: 'delete',
                    caption: '删除',
                  },
                ],
              },
              {
                key: 'render',
                label: 'render',
                'min-width': 130,
                render(h, { row, column, index }) {
                  return h('div', [
                    ...(row.value ? [] : [h('el-button', { key: 1 }, '编辑')]),
                    ...(_this.isShowDelBtn
                      ? []
                      : [h('el-button', { key: 2 }, '删除')]),
                    h(
                      'el-button',
                      {
                        directives: [
                          {
                            name: 'bgcolor',
                            value: row.value ? 'red' : 'blue',
                          },
                        ],
                        key: 3,
                      },
                      '新增'
                    ),
                  ])
                },
              },
            ],
            list: Array(10)
              .fill()
              .map((i, index) => ({
                id: index,
                name: `name${index}`,
                value:
                  JsGlobalConstants.length > index
                    ? JsGlobalConstants[index]
                    : `value${index}`,
              })),
            taskName: '',
          }
        },
        methods: {
          handleSelectionChange(val) {
            alert('[handleSelectionChange]', val)
          },
          handleButtonClick(btnKey, index, row) {
            alert(`btnKey: ${btnKey}, index: ${index}, row: ${row}`)
          },
          getName(row) {
            return `我是${row.name}`
          },
          runTestTask({ name, todo, nextTask }) {
            return new Promise((resolve, reject) => {
              try {
                setTimeout(() => {
                  this.taskName = name
                  todo()
                  resolve()
                }, 2000)
              } catch (err) {
                reject(err)
              }
            })
          },
          async runTestTasks(tasks) {
            let currentTaskIndex = 0
            while (currentTaskIndex < tasks.length) {
              await this.runTestTask(tasks[currentTaskIndex])
              currentTaskIndex++
            }
          },
          testColumnsUpdate() {
            let targetColumnIndex = this.columns.findIndex(
              (item) => item.key === 'name-caption-string'
            )
            const tasks = [
              {
                name: '更新key: name-caption-string 列配置的 caption',
                todo: () => {
                  this.columnMap['name-caption-string'].caption = '222'
                },
              },
              {
                name: '移除key: name-caption-string 列配置',
                todo: () => {
                  this.columns.splice(targetColumnIndex, 1)
                },
              },
              {
                name: '添加key: name-caption-string 列配置',
                todo: () => {
                  this.columns.splice(targetColumnIndex, 0, {
                    key: 'name-caption-string',
                    label: 'name-caption-string',
                    caption: '111',
                  })
                },
              },
            ]
            this.runTestTasks(tasks)
          },
          getSummaries ({ columns, data }) {
            const sumList = Array(columns.length).fill(10)
            console.log('sumList', sumList)
            return sumList
          },
          changeTableDataHandler () {
            this.list = Array(100)
              .fill()
              .map((i, index) => ({
                id: index,
                name: `name--${index}`,
                value:
                  JsGlobalConstants.length > index
                    ? JsGlobalConstants[index]
                    : `value--${index}`,
              }))
          }
        },
        mounted() {
          this.columnMap = this.columns.reduce((acc, item) => ({
            ...acc,
            [item.key]: item,
          }))
          console.log('tableVm', this.$refs['tn-eltable'].tableVm)
        },
      })
    </script>
  </body>
</html>
